<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>精彩图集</title>
    <link rel="stylesheet" href="/css/mobile/index.css">
    <link rel="stylesheet" href="/css/mobile/atlas/atlasaddimg.css">
    <!-- 重置默认样式 -->
    <link rel="stylesheet" href="/css/resetcss.css">

    <style>
            
        
    </style>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar">
        <div class="navbar-container">
            <div class="nav-item active">
                <a href="#" class="nav-home">
                    <i class="fas fa-home"></i>
                    <span>主页</span>
                </a>
            </div>
            <div class="nav-item">
                <a href="#" class="nav-life">
                    <i class="fas fa-camera"></i>
                    <span>生活瞬间</span>
                </a>
            </div>
            <div class="nav-item">
                <a href="#" class="nav-tour">
                    <i class="fas fa-plane"></i>
                    <span>旅行记录</span>
                </a>
            </div>
            <div class="nav-item">
                <a href="#" class="nav-atlas">
                    <i class="fas fa-images"></i>
                    <span>精彩图集</span>
                </a>
            </div>
            <div class="nav-item">
                <a href="#" class="nav-center">
                    <i class="fas fa-user"></i>
                    <span>个人中心</span>
                </a>
            </div>
        </div>
    </nav>


    <!-- 内容区域 -->
    <div class="upload-container">
        <!-- 提交按钮 -->
        <div class="mobile-submit-container">
            <button class="mobile-submit-btn" id="submitBtn">
              <span class="btn-text">提交</span>
              <span class="loading-spinner" style="display: none;"></span>
            </button>
        </div>

        <!-- 单图上传区域 -->
        <div class="single-upload">
            <div class="upload-icon">+</div>
            <div class="upload-text">点击上传封面图片</div>
            <button class="upload-button" style="background: #4285f4; color: white; border: none; padding: 10px 20px; border-radius: 6px; font-size: 14px;">
                选择图片
            </button>
            <input type="file" class="single-file" accept="image/*">
            <img src="#" alt="上传的图片" class="single-uploadimg">
        </div>
        
        <!-- 标题和描述区域 -->
        <div class="info-section">
            <div class="input-group">
                <label for="title">标题</label>
                <input type="text" id="title" placeholder="请输入标题">
            </div>
            <div class="input-group">
                <label for="description">描述</label>
                <textarea id="description" placeholder="请输入描述..."></textarea>
            </div>
        </div>
        
        <!-- 多图上传区域 -->
        <div class="multi-upload">
            <div class="mobile-image-uploader">
                <!-- 上传按钮 -->
                <input type="file" id="imageUpload" accept="image/*" multiple style="display: none;">
                <button class="upload-btn" id="uploadButton">+ 上传图片</button>
                
                <!-- 提示文字 -->
                <p class="hint-text">最多可上传20张图片</p>
                
                <!-- 预览区域 -->
                <div class="preview-container" id="previewContainer"></div>
            </div>
        </div>
    </div>
</body>


<script src="https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js"></script>
<script src="/configfile/config.js"></script>
<script type="module">

	//window.__ENV__   这样来读取env环境变量里面公开出来的变量

	//获取导航的a标签，并设置href
	const navhome = document.querySelector('.nav-home'); // 返回第一个匹配的节点
	const navlife = document.querySelector('.nav-life'); // 返回第一个匹配的节点
	const navatlas = document.querySelector('.nav-atlas'); // 返回第一个匹配的节点
	const navcenter = document.querySelector('.nav-center');//获取个人中心DOM


	let server_ip = window.__ENV__.SERVER_IP;//服务器ip
	let home_ip = window.__ENV__.HOME_SERVER_IP;//首页ip
	navhome.href = home_ip;
	let life_ip = window.__ENV__.LIFEMOMENT_SERVER_IP;//生活瞬间
	navlife.href = life_ip;
	let atlas_ip = window.__ENV__.ATLAS_SERVER_IP;//图片集
	navatlas.href = atlas_ip;
	let user_ip = window.__ENV__.USER_SERVER_IP;//用户
    navcenter.href = user_ip;

	//获取令牌
	let token = localStorage.getItem("token");

    //使用ejs模版来返回数据
    let resultData = <%- JSON.stringify(json) %>;


    // 简单的导航栏交互效果
    document.querySelectorAll('.nav-item').forEach(item => {
        item.addEventListener('click', function() {
            document.querySelector('.nav-item.active').classList.remove('active');
            this.classList.add('active');
        });
    });

    let title = document.getElementById("title");
    let description = document.getElementById("description");
    //赋值数据
    (function(){
        title.value = resultData.Atlasname;
        description.value = resultData.Atlasdescription;
    })();

    //绑定选择图片方法
    let singleupload = document.querySelector(".single-upload");//div
    let singlefile = document.querySelector(".single-file");//input
    let uploadicon = document.querySelector(".upload-icon");
    let uploadtext = document.querySelector(".upload-text");
    let uploadbutton = document.querySelector(".upload-button");
    let singleuploadimg = document.querySelector(".single-uploadimg");//img


    function singleimg(){
        singlefile.click();
    }
    singleupload.addEventListener("click", singleimg);

    singlefile.addEventListener("change",()=>{
        // 1. 检查是否有文件被选中
        if (!singlefile.files || singlefile.files.length === 0) {
            console.log('没有选择文件');
            return;
        }
        let file = singlefile.files[0];
        const reader = new FileReader();
        reader.onload = (e) => {
            singleuploadimg.src = e.target.result;
            singleuploadimg.style.display = "block";
        };
        uploadicon.style.display = "none";
        uploadtext.style.display = "none";
        uploadbutton.style.display = "none";
        reader.readAsDataURL(file);
    });

    //赋值图片封面
    (function(){
        singleuploadimg.src = server_ip + "/" + resultData.Atlascoverurl;
        singleuploadimg.style.display = "block";
        
        uploadicon.style.display = "none";
        uploadtext.style.display = "none";
        uploadbutton.style.display = "none";
    })();


    //多张图片
    // 获取DOM元素
    const uploadButton = document.getElementById('uploadButton');
    const imageUpload = document.getElementById('imageUpload');
    const previewContainer = document.getElementById('previewContainer');
    const MAX_IMAGES = 20;
    let arrayuploadimg = [];
    
    // 点击按钮触发文件选择
    uploadButton.addEventListener('click', () => {
      // 计算还能上传多少张图片
      const currentCount = previewContainer.querySelectorAll('.thumbnail:not(.thumbnail-placeholder)').length;
      if (currentCount >= MAX_IMAGES) {
        alert(`最多只能上传${MAX_IMAGES}张图片`);
        return;
      }
      imageUpload.click();
    });
    
    // 文件选择变化时的处理
    imageUpload.addEventListener('change', (e) => {
      const files = e.target.files;
        for(let i=0; i<files.length; i++){
            arrayuploadimg.push(files[i]);
        }
      if (!files || files.length === 0) return;
      
      // 检查总数是否超过限制
      const currentCount = previewContainer.querySelectorAll('.thumbnail:not(.thumbnail-placeholder)').length;
      const remainingSlots = MAX_IMAGES - currentCount;
      
      if (files.length > remainingSlots) {
        alert(`最多还能上传${remainingSlots}张图片`);
        return;
      }
      
      // 处理每个文件
      Array.from(files).slice(0, remainingSlots).forEach(file => {
        if (!file.type.startsWith('image/')) return;
        
        const thumbnail = document.createElement('div');
        thumbnail.className = 'thumbnail';
        
        const img = document.createElement('img');
        img.src = URL.createObjectURL(file);
        
        const deleteBtn = document.createElement('div');
        deleteBtn.className = 'delete-btn';
        deleteBtn.innerHTML = '×';
        deleteBtn.addEventListener('click', (e) => {
          e.stopPropagation();
          thumbnail.remove();
          updatePlaceholder();
        });
        
        thumbnail.appendChild(img);
        thumbnail.appendChild(deleteBtn);
        previewContainer.insertBefore(thumbnail, previewContainer.lastElementChild);
      });
      
      updatePlaceholder();
    //   imageUpload.value = ''; // 重置input，允许重复选择相同文件
    });
    
    // 更新占位符显示
    function updatePlaceholder() {
      // 移除现有占位符
      const existingPlaceholder = previewContainer.querySelector('.thumbnail-placeholder');
      if (existingPlaceholder) existingPlaceholder.remove();
      
      // 如果未满，添加占位符
      const currentCount = previewContainer.querySelectorAll('.thumbnail:not(.thumbnail-placeholder)').length;
      if (currentCount < MAX_IMAGES) {
        const placeholder = document.createElement('div');
        placeholder.className = 'thumbnail thumbnail-placeholder';
        placeholder.innerHTML = '+';
        placeholder.addEventListener('click', () => uploadButton.click());
        previewContainer.appendChild(placeholder);
      }
    }
    
    // 初始化占位符
    updatePlaceholder();

    //提交后端
    function submitUpdataAtlas(){
        //构建form表单，浏览器的方法
        let formData = new FormData();
        formData.append("singleImg",singlefile.files[0]);
        for(let i=0; i<arrayuploadimg.length; i++){
            formData.append("arrayImg",arrayuploadimg[i]);
        }
        formData.append("Atlasname",title.value);
        formData.append("Atlasmessage",description.value);
        
        // 提交时的加载状态示例
        const btn = this;
        btn.disabled = true;
        btn.querySelector('.btn-text').textContent = '提交中';
        btn.querySelector('.loading-spinner').style.display = 'inline-block';
        
        axios
            .post(
                atlas_ip+"/updataatlas" + resultData.Atlas_id,
                formData,
                {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        "Authorization": `Bearer ${token}`
                    },
                }
            )
            .then((res) => {
                //判断后端的报错信息。如果存在则保存失败
                // console.log(res.data);
                if(res.data.message.success){
                    btn.disabled = false;
                    btn.querySelector('.btn-text').textContent = '提交成功';
                    btn.querySelector('.loading-spinner').style.display = 'none';
                }
            })
            .catch(err => {
                console.log(err);
                alert("保存失败")
            });
    }

    let submitBtn = document.getElementById('submitBtn')
    submitBtn.addEventListener("click", submitUpdataAtlas);

</script>
</html>